package com.lanchetech.merchant.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.bean.request.ActivityBindSpuReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.response.SpuResp;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.SkuItemVO;
import com.lanchetech.common.constants.BaseConstant;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.dao.ActivityBindSpuMapper;
import com.lanchetech.dao.ActivityMapper;
import com.lanchetech.dao.SkuMapper;
import com.lanchetech.dao.SpuMapper;
import com.lanchetech.entity.*;

import com.lanchetech.merchant.service.ActivityBindSpuService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ActivityBindSpuServiceImpl extends ServiceImpl<ActivityBindSpuMapper, ActivityBindSpu> implements ActivityBindSpuService {

    @Resource
    private ActivityBindSpuMapper bindSpuMapper;
    @Resource
    private SpuMapper spuMapper;
    @Resource
    private SkuMapper skuMapper;
    @Resource
    private ActivityMapper activityMapper;

    @Override
    public BaseResp bindSpu(ActivityBindSpu bindSpu) {
        if (Objects.isNull(bindSpu.getId())) {
            int size = bindSpuMapper.getList(bindSpu).size();
            if (size > BaseConstant.ZERO) {
                return new BaseResp(ResultCode.SKU_IS_EXIST);
            }
            save(bindSpu);
        }else {
            updateById(bindSpu);
        }
        return new BaseResp();
    }


    @Override
    public BaseResp unBindSpu(Long id) {
        ActivityBindSpu byId = getById(id);
        if (Objects.isNull(byId)) {
            return new BaseResp(ResultCode.BIND_SKU_IS_NULL);
        }
        if (byId.getIsDeleted().equals(BaseConstant.ONE)) {
            byId.setIsDeleted(BaseConstant.ZERO);
        } else {
            byId.setIsDeleted(BaseConstant.ONE);
        }
        updateById(byId);
        return new BaseResp();
    }


    @Override
    public ResultData<BasePageResp<ActivityBindSpu>> getPage(ActivityBindSpuReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        ActivityBindSpu bindSpu = new ActivityBindSpu();
        bindSpu.setActivityId(req.getActivityId());
        List<ActivityBindSpu> list = bindSpuMapper.getList(bindSpu);
        return PageHelpUtil.buildPage(list, page);
    }

    @Override
    public ResultData<BasePageResp<SpuResp>> getBindPage(ActivityBindSpuReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        Merchant merchant = (Merchant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        req.setTenantId(merchant.getTenantId());
        List<SpuResp> respList = new ArrayList<>();
        List<ActivityBindSpu> list = bindSpuMapper.getMerchantList(req);
        if (CollectionUtils.isNotEmpty(list)) {
            // 处理spuIds
            List<Long> spuIds = list.stream().map(ActivityBindSpu::getSpuId).distinct().collect(Collectors.toList());
            List<Spu> spuList = spuMapper.findAllByIds(spuIds);

            // 活动信息
            Map<Long, Long> collect = list.stream().collect(Collectors.toMap(ActivityBindSpu::getSpuId, ActivityBindSpu::getActivityId, (t1, t2) -> t1));
            List<Activity> activities = activityMapper.selectBatchIds(list.stream().map(ActivityBindSpu::getActivityId).distinct().collect(Collectors.toList()));
            Map<Long, Activity> activityMap = activities.stream().collect(Collectors.toMap(Activity::getId, s -> s, (t1, t2) -> t1));
            spuList.forEach(s -> {
                SpuResp resp = new SpuResp();
                BeanUtils.copyProperties(s, resp);
                Long activityId = collect.get(resp.getId());
                Activity activity = activityMap.get(activityId);
                resp.setActivityId(activityId);
                resp.setActivityType(activity.getType());
                respList.add(resp);
            });
            // 新人专区活动价格和 活动库存
            Map<Long, ActivityBindSpu> newPriceMap = list.stream().collect(Collectors.toMap(ActivityBindSpu::getSkuId, s->s, (t1, t2) -> t1));
            List<Long> skuIds = list.stream().map(ActivityBindSpu::getSkuId).collect(Collectors.toList());
            List<Sku> skuList = skuMapper.findAllByIds(skuIds);
            List<SkuItemVO> skuItemVOList = new ArrayList<>();
            for (Sku sku : skuList) {
                SkuItemVO itemVO = new SkuItemVO();
                BeanUtils.copyProperties(sku, itemVO);
                itemVO.setNewPrice(newPriceMap.get(itemVO.getId()).getNewPrice());
                itemVO.setActivityStock(newPriceMap.get(itemVO.getId()).getActivityStock());
                skuItemVOList.add(itemVO);
            }
            Map<Long, List<SkuItemVO>> skuMap = skuItemVOList.stream().collect(Collectors.groupingBy(SkuItemVO::getSpuId));
            respList.forEach(t -> t.setSkuItemVOS(skuMap.get(t.getId())));
        }
        return PageHelpUtil.buildPage(respList, page);
    }
}
